<template>
  <div>
    <UiBreadcrumbs
      :items="breadcrumbs"
      class="_breadcrumbs-info _container"
    />
    <ViewModelVideos
      :data="data"
      :title="h1"
      :status="status"
      :card-info="cardInfo"
      :data-models="dataModels"
      :model-tags="modelTags"
      :model-channels="modelChannels"
      :similar-models="topModels?.items"
    />
  </div>
</template>

<script setup lang="ts">
import { convertQueryCategories, convertString, AsyncData } from '../../../runtime';
import { VideosApiService } from '../../../services/api/videos.service';
import { ModelsApiService } from '../../../services/api/models.service';
import { ChannelsApiService } from '../../../services/api/channels.service';
import type { IBreadcrumbItem } from '../../../types';
import { sortItemsDefault } from '../../../lib';

const route = useRoute();

const pageName = useGetPureRouteName();

const [
  { data, status },
  { data: cardInfo },
  { data: dataModels },
  { data: modelTags },
  { data: modelChannels },
  { data: topModels }, // TODO placeholder
] = await Promise.all([
  useFetchVideosByModel(VideosApiService.getListByNicheAndModel),
  useFetchModelByName(ModelsApiService.getModelsByName),
  useFetchRelatedModels(ModelsApiService.getRelatedModels, 25, String(pageName)),
  useFetchPopularTagsByModelName(VideosApiService.popularTagsByModelName),
  useFetchChannelsByModel(ChannelsApiService.getChannelsByModel),
  useFetchTopModels(ModelsApiService.getTop, 12, AsyncData.TopModelsMore, String(pageName)),
]);

const testModelImages = [
  '/img/models/Austin_Young.png',
  '/img/models/Dakota_Lovell.png',
  '/img/models/Devin_Franco.png',
  '/img/models/Falcon_Al.png',
  '/img/models/Jax_Thirio.png',
  '/img/models/LeGrand_Wolf.png',
  '/img/models/Oliver_Strelly.png',
  '/img/models/Roman_Todd.png',
  '/img/models/Sebastian _Kane.png',
];

if (cardInfo.value) {
  cardInfo.value.img = testModelImages[Math.floor(Math.random() * testModelImages.length)];
}

const { t } = useI18n();

const title = convertString().fromSlug(String(route.params[ 'slug' ]));
const metaTitle = computed(() => convertString().toCapitalize(title));

const routeQueryCategories = computed(() => {
  if (route.query[ 'categories' ]) {
    const text = convertQueryCategories(route);
    return ` ${convertString().toCapitalize(text)}`;
  }
  return '';
});

const { meta, h1 } = useMeta({
  t,
  pageKey: pageName,
  brandName: useAppConfig().brandName,
  sortOptions: sortItemsDefault,
  text: metaTitle,
  secondText: routeQueryCategories,
  seo: () => cardInfo.value?.seo,
});

const breadcrumbs: IBreadcrumbItem[] = [
  {
    name: `${t('navigation.main')}`,
    to: '/',
  },
  {
    name: `${t('navigation.models')}`,
    to: '/models',
  },
  {
    name: title,
  },
];

watchEffect(() => {
  useHead(meta.value);

  if (status.value === 'success' && !cardInfo.value) {
    throw createError({ statusCode: 404, statusMessage: 'Not Found' });
  }
});
</script>
